import '../public.dart';

class UserModel extends ChangeNotifier {
  bool get isLogin => StorageManager.getItem('token') != null;
  String? pinVerifyCode;

  ClientProfileDto? userInfo;

  int availableBalance = 0;

  bool isBalanceHidden = true;

  bool hasPin = false;

  bool isInit = false;

  bool get bankCardEmpty => bankCardList.isEmpty;

  String get displayBalance {
    if (isBalanceHidden) {
      return '***.**';
    }
    // 正常显示时添加千分位分隔符
    return FmtUtil.formatBalanceWithThousandSeparators(
      availableBalance.toString(),
    );
  }

  List<WithdrawBankCardComboxDto> bankCardList = [];

  Future<void> getUserInfo() async {
    final info = await ClientUserApi.getProfile();
    userInfo = info.content;
    notifyListeners();
  }

  // 查询用户余额
  Future<void> getBalance() async {
    final info = await ClientUserApi.getAvailableBalance();
    availableBalance = info.content ?? 0;
    notifyListeners();
  }

  /// 查询用户是否有pin
  Future<bool> checkPin() async {
    final info = await ClientUserApi.queryPinExists();
    hasPin = info.content?.binExists ?? false;
    pinVerifyCode = CryptoUtil.decryptData(info.content?.verifyCode);
    notifyListeners();
    return hasPin;
  }

  /// 查询用户银行卡列表
  Future<bool> getBankCardList() async {
    // 查询银行卡列表
    final response = await BankCardApi.getListByUser();
    bankCardList = response.content ?? [];
    notifyListeners();
    return Future.value(true);
  }

  /// 切换余额显示状态
  void toggleBalanceHidden() {
    isBalanceHidden = !isBalanceHidden;
    notifyListeners();
  }

  Future<bool> init() async {
    try {
      if (isLogin) {
        await getUserInfo();
        await getBalance();
        await getBankCardList();
        await checkPin();
      }
      return Future.value(true);
    } catch (e) {
      Toast.show('Get User Info Failed: $e');
      StorageManager.ls.clear();
      RouterHelper.navigator.pushReplacementNamed(Routers.login);
      return Future.error(e);
    } finally {
      isInit = true;
      notifyListeners();
    }
  }
}
